﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Videos;
using SIG.Model;
using SIG.Model.Enums;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Videos;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SIG.Model.Videos;
using System.Xml.Linq;
using System.Linq;
using SIG.Resources.Admin;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class VideoController : BaseController
    {
        private readonly IVideoService _videoService;

        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public VideoController(IVideoService videoService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _videoService = videoService;

            _pageMetaService = pageMetaService;
            _mapper = mapper;

        }
        // GET: Admin/Video

        #region Video

        public ActionResult Index(int? page, string keyword)
        {
            VideoListVM videoListVM = GetElements(page, keyword);
         
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(videoListVM);

        }

        private VideoListVM GetElements(int? page, string keyword)
        {
            var videoListVM = new VideoListVM();

            videoListVM.Keyword = keyword;
            videoListVM.PageIndex = (page ?? 1) - 1;
            videoListVM.PageSize = SettingsManager.Video.PageSize;
            int totalCount;
            var videolist = _videoService.GetPagedElements(videoListVM.PageIndex, videoListVM.PageSize, videoListVM.Keyword, out totalCount);
            var videoVMList = _mapper.Map<List<Video>, List<VideoVM>>(videolist);
            videoListVM.TotalCount = totalCount;
            videoListVM.Videos = new StaticPagedList<VideoVM>(videoVMList, videoListVM.PageIndex + 1, videoListVM.PageSize, videoListVM.TotalCount); ;
            return videoListVM;
        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/VideoSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        [HttpGet]
        public ActionResult Add()
        {
            var vCategory = new VideoIM();
            vCategory.Active = true;
            //vCategory.PageIndex = pageIndex;
            //vCategory.PageSize = pageSize;
            //vCategory.Keyword = keyword;


            return PartialView("_Add", vCategory);
        }



        [HttpPost]
        public JsonResult Add(VideoIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var video = _mapper.Map<VideoIM, Video>(vm);
            _videoService.Create(video);

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.Description))
            {
                var pageMeta = new PageMeta()
                {
                    ObjectId = video.Id,
                    Keyword = vm.Keywords.Replace('，', ','),
                    Description = vm.Description,
                    ModelType = ModelType.VIDEO
                };
                _pageMetaService.Create(pageMeta);
            }

            int count;
            int pageSize = SettingsManager.Video.PageSize;
            var list = _videoService.GetPagedElements(0, pageSize, string.Empty,out count);
            List<VideoVM> videoList = _mapper.Map<List<Video>, List<VideoVM>>(list);
            AR.Data = RenderPartialViewToString("_VideoList", videoList);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Video));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Video video = _videoService.GetById(id);
            if (video == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<VideoIM>(video);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.VIDEO, vm.Id);
            if (pageMeta != null)
            {
                vm.Keywords = pageMeta.Keyword;
                vm.Description = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(VideoIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var video = _videoService.GetById(vm.Id);
            video.Active = vm.Active;
            video.VideoUrl = vm.VideoUrl;
            video.Title = vm.Title;
            video.Thumbnail = vm.Thumbnail;
            video.Preview = vm.Preview;
            //video = _mapper.Map<VideoIM, Video>(vm);
            _videoService.Update(video);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.VIDEO, vm.Id);
            pageMeta = pageMeta ?? new PageMeta();

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.Description))
            {

                pageMeta.ObjectId = vm.Id;
                pageMeta.Keyword = vm.Keywords;
                pageMeta.Description = vm.Description;
                pageMeta.ModelType = ModelType.VIDEO;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
            }


            var videoVM = _mapper.Map<VideoVM>(video);

            AR.Id = video.Id;
            AR.Data = RenderPartialViewToString("_VideoItem", videoVM);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Video));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Video vCategory = _videoService.GetById(id);
                     

            _videoService.Delete(vCategory);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Video));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vCategory = _videoService.GetById(id);
            if (vCategory == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vCategory.Active = !vCategory.Active;
                _videoService.Update(vCategory);
                var vm = _mapper.Map<VideoVM>(vCategory);

                AR.Data = RenderPartialViewToString("_VideoItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Video));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        


        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _videoService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}



        #endregion
    }
}